﻿using AlarmClock.DAL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;

namespace AlarmClock.BLL
{
    public class ClockBLL
    {
        /// <summary>
        /// 闹钟服务 DAL层
        /// </summary>
        private ClockService clockService = new ClockService();

        /// <summary>
        /// 创建一个xml文档（路径不全的情况下默认保存在debug文件夹中）
        /// </summary>
        /// <param name="XMLPath"></param>
        public void CreateClocksXML(string XMLPath = "Clocks.xml")
        {
            clockService.CreateClocksXML(XMLPath);
        }

        /// <summary>
        /// 增加新数据到xml文档中（路径不全的情况下默认添加在debug文件夹中）
        /// </summary>
        /// <param name="clock">新数据</param>
        /// <param name="XMLPath">文件路径。默认：Clocks.xml</param>
        public void InsertClock(Clock clock, string XMLPath = "Clocks.xml")
        {
            clockService.InsertClock(Service.ClockToEntity(clock), XMLPath);
        }

        /// <summary>
        /// 删除xml文档的指定数据（路径不全的情况下默认删除在debug文件夹中）
        /// </summary>
        /// <param name="clock">指定数据</param>
        /// <param name="XMLPath">文件路径。默认：Clocks.xml</param>
        public void DeleteClock(Clock clock, string XMLPath = "Clocks.xml")
        {
            clockService.DeleteClock(Service.ClockToEntity(clock), XMLPath);
        }

        /// <summary>
        /// 查询全部闹钟数据
        /// </summary>
        /// <param name="XMLPath">文件路径。默认：Clocks.xml</param>
        /// <param name="rootName">根节点名称。默认：Clocks</param>
        /// <returns></returns>
        public List<Clock> ReadAllClockInfo(string XMLPath = "Clocks.xml", string rootName = "Clocks")
        {
            return Service.ClockListToModel(clockService.ReadAllClockInfo(XMLPath, rootName)); 
        }

        /// <summary>
        /// 读取全局配置信息
        /// </summary>
        /// <param name="XMLPath">文件路径。默认：Clocks.xml</param>
        /// <param name="rootName">根节点名称。默认：Clocks</param>
        /// <returns></returns>
        public ClockConfig ReadAllClockConfig(string XMLPath = "Clocks.xml", string rootName = "ClockConfig")
        {
            return Service.ClockConfigToModel(clockService.ReadAllClockConfig(XMLPath, rootName));
        }

        /// <summary>
        /// 修改指定闹钟数据（路径不全的情况下默认更新在debug文件夹中）
        /// </summary>
        /// <param name="clock">指定数据</param>
        /// <param name="XMLPath">文件路径。默认：Clocks.xml</param>
        public void UpdateClock(Clock clock, string XMLPath = "Clocks.xml")
        {
            clockService.UpdateClock(Service.ClockToEntity(clock), XMLPath);
        }

        /// <summary>
        /// 距离当前【闹钟】响的时差
        /// </summary>
        /// <param name="curTime"></param>
        /// <returns>【0】：天数差。【1】：小时差。【2】：分钟差。【3】：秒钟差。</returns>
        public DateTimeDiff GetMinDisTime(string curTime = "")
        {
            //激活闹钟数量=0，直接归0
            var clocks = clockService.ReadAllClockInfo().Where(p => p.ClockInfo.isActive == "1").ToList();
            if (clocks.Count == 0)
            {
                return null;
            }
            DateTime now = DateTime.Now;
            DateTime recentTime;
            if (curTime != "") recentTime = DateTime.Parse(curTime);
            else recentTime = DateTime.Parse(clockService.ReadAllClockConfig().recentTime);

            TimeSpan timeDis = recentTime - now;
            return new DateTimeDiff()
            {
                Day = timeDis.Days,
                Hour = timeDis.Hours,
                Minute = timeDis.Minutes,
                Second = timeDis.Seconds,
            };
        }

        /// <summary>
        /// 最近时间更新+更新过期时间
        /// </summary>
        /// <param name="curTime">传入时间</param>
        public void UpdateRecentTime(List<Clock> Clocks)
        {
            //读取全部配置信息
            var AllConfig=clockService.ReadAllClockConfig();
            //当前时间
            DateTime now = DateTime.Now;

            List<Clock> ClockList=Clocks.Where(p => p.clockInfo.isActive=="1").ToList();           
            if (ClockList.Count == 0)
            {
                clockService.UpdateClockConfig(AllConfig);
                return;
            }

            AllConfig.recentTime = "";
            foreach (var clock in ClockList)
            {
                //更新过期时间
                string next = clock.clockInfo.repeat.Trim();
                var dtTime = DateTime.Parse(clock.clockInfo.time);
                if (dtTime < DateTime.Now)
                {
                    switch (next)
                    {
                        case "每天":
                            while (dtTime < DateTime.Now) dtTime = dtTime.AddDays(1);
                            break;
                        case "每周":
                            while (dtTime < DateTime.Now) dtTime = dtTime.AddDays(7);
                            break;
                        case "每月":
                            while (dtTime < DateTime.Now) dtTime = dtTime.AddMonths(1);
                            break;
                        case "自定义":
                            break;
                        case "法定工作日（自动跳过节假日）":
                            break;
                        case "不重复":
                        default:
                            int add_Number = -1;
                            if (next.Any(char.IsDigit) && next.Length >= 3)
                            {
                                _ = int.TryParse(next.Substring(1, next.Length - 2), out add_Number);
                            }
                            if (add_Number != -1)
                            {
                                for (int i = 0; i < add_Number; i++)
                                {
                                    if (next.Contains("天"))
                                    {
                                        dtTime = dtTime.AddDays(1);
                                    }
                                    else if (next.Contains("周"))
                                    {
                                        dtTime = dtTime.AddDays(7);
                                    }
                                    else if (next.Contains("月"))
                                    {
                                        dtTime = dtTime.AddMonths(1);
                                    }
                                }
                                break;
                            }
                            break;
                    }
                    clock.clockInfo.time = $"{dtTime.ToString("yyyy-MM-dd HH:mm:ss")}";
                    UpdateClock(clock);
                }

                if (string.IsNullOrEmpty(AllConfig.recentTime))
                {
                    AllConfig.recentTime = clock.clockInfo.time;
                    continue;
                }
                DateTime clockD = DateTime.Parse(clock.clockInfo.time);
                DateTime recentD = DateTime.Parse(AllConfig.recentTime);

                if (clockD < recentD)
                {
                    AllConfig.recentTime = clock.clockInfo.time;//更新最近时间
                }
            }

            clockService.UpdateClockConfig(AllConfig);
        }


        /// <summary>
        /// 修改闹钟全局配置数据
        /// </summary>
        /// <param name="Config">配置数据</param>
        /// <param name="XMLPath">文件路径。默认：Clocks.xml</param>
        public void UpdateClockConfig(Model.ClockConfig Config, string XMLPath = "Clocks.xml")
        {
            clockService.UpdateClockConfig(Service.ClockConfigToEntity(Config), XMLPath);
        }
    }
}
